package cn.yuanqiao.archive.task.impl;

import cn.yuanqiao.archive.appManager.domain.TenantSysConfig;
import cn.yuanqiao.archive.appManager.mapper.TenantSysConfigMapper;

import cn.yuanqiao.archive.task.SyncTaskZTService;
import cn.yuanqiao.archive.task.util.SyncTaskZTUtils;
import cn.yuanqiao.common.constant.SecurityConstants;
import cn.yuanqiao.common.core.domain.R;
import cn.yuanqiao.common.utils.MD5Utils;
import cn.yuanqiao.common.utils.StringUtils;
import cn.yuanqiao.common.core.domain.model.LoginUser;
import cn.yuanqiao.system.service.ISysUserService;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

@Service
public class SyncTaskZTServiceImpl implements SyncTaskZTService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private TenantSysConfigMapper tenantSysConfigMapper;

    @Autowired
    private ISysUserService remoteUserService;

    @Override
    public void syncTask(Map<String, Object> map) {
        try {
            TenantSysConfig config = new TenantSysConfig();
            config.setTenantCode(String.valueOf(map.get("tenantId")));
            config.setConfigKey("SYNC_TASK_ZT");
            TenantSysConfig sysConfig = tenantSysConfigMapper.selectConfig(config);
            if(sysConfig!=null && StringUtils.isNotEmpty(sysConfig.getConfigValue()) && "true".equals(sysConfig.getConfigValue())){
                JSONObject data = new JSONObject();
                //否 业务功能编码，对应系统菜单编码，与应用入驻中应用系统功能编码保持一致。
                //config.setConfigKey("bizCode");
                //String bizCode = tenantSysConfigMapper.selectConfig(config).getConfigValue();
                String bizCode = "";
                data.put("bizCode",bizCode);
                //否 业务功能名称，对应系统菜单名称，与应用入驻中应用系统功能编码保持一致。
                //config.setConfigKey("bizName");
                //String bizName = tenantSysConfigMapper.selectConfig(config).getConfigValue();
                String bizName = "";
                data.put("bizName",bizName);
                //否 流程编码，如果没有，则填写业务功能编码
                String flowCode = (String) map.get("processDefinitionKey");
                data.put("flowCode",flowCode);
                //否 流程名称，如果没有，则填写业务功能名称
                String flowName = (String) map.get("processDefinitionName");
                data.put("flowName",flowName);
                //是 流程类别，DS：待办、DY：待阅、YS：已办、YY：已阅
                String pType = (String) map.get("pType");
                data.put("pType",pType);
                //是 源应用系统流程实例ID
                String workflowId = (String) map.get("processInstanceId");
                data.put("workflowId",workflowId);
                //否 应用系统的流程单据号
                String formNo = "";
                data.put("formNo",formNo);
                //是 源应用系统待办ID/任务ID
                String pId = (String) map.get("taskId");
                data.put("pId",pId);
                //是 标题
                String pTitle = (String) map.get("taskName");
                data.put("pTitle",pTitle);
                //否 流程事项描述
                String pDesc = "";
                data.put("pDesc",pDesc);
                //是 当前消息发起时间（上个节点的处理时间），日期格式如下:yyyy-MM-dd HH:mm:ss
                String pDateTime = String.valueOf(map.get("startTime"));
                data.put("pDateTime",pDateTime);
                //否 流程发起人Id，必须统一身份的ID
                String tenantId = (String) map.get("tenantId");
                String assignee = (String) map.get("assignee");
                LoginUser assigneeUserInfo = remoteUserService.getUserInfo(assignee, tenantId);
                String startUserId = (String) map.get("startUserId");
                LoginUser startUserInfo = remoteUserService.getUserInfo(startUserId, tenantId);
                String pCreatorId = startUserInfo==null?"":startUserInfo.getUser().getOneId();
                data.put("pCreatorId",pCreatorId);
                //否 流程发起人名称
                String pCreatorName = startUserInfo==null?"":startUserInfo.getUser().getNickName();
                data.put("pCreatorName",pCreatorName);
                //是 流程处理人ID，必须统一身份的ID。
                String pToUserId = assigneeUserInfo==null?"":assigneeUserInfo.getUser().getOneId();
                data.put("pToUserId",pToUserId);
                //是 流程处理人姓名
                String pToUserName = assigneeUserInfo==null?"":assigneeUserInfo.getUser().getNickName();
                data.put("pToUserName",pToUserName);
                //否 当前节点办理时间，日期格式如下:yyyy-MM-dd HH:mm:ss
                String pEndDateTime = map.get("endTime") == null ? "":String.valueOf(map.get("endTime"));
                data.put("pEndDateTime",pEndDateTime);
                //是 默认PC端待办信息处理URL，应用系统提供相对的URL
                config.setConfigKey("SYSTEM_URL");
                String SYSTEM_URL = tenantSysConfigMapper.selectConfig(config).getConfigValue();
                //http://192.168.2.55/login?redirect=/task/task?taskId=
                String pcUrl = (SYSTEM_URL+"/task/task?taskId="+map.get("taskId"));
                data.put("pcUrl",pcUrl);
                //否 MOBILE端待办信息处理URL，应用系统提供相对的URL
                config.setConfigKey("SYSTEM_URL_MOBILE");
                String SYSTEM_URL_MOBILE = tenantSysConfigMapper.selectConfig(config).getConfigValue();
                String mobileUrl = SYSTEM_URL_MOBILE;
                if("WorkFlow_Archive_Borrow".equals(map.get("processDefinitionKey"))){
                    //借阅
                    if("YS".equals(pType)){
                        mobileUrl = mobileUrl + "/dangan/#/dandianLogin?toName=borrowYB&taskId="+map.get("taskId");
                    }else {
                        mobileUrl = mobileUrl + "/dangan/#/dandianLogin?toName=borrowApplication&taskId="+map.get("taskId");
                    }
                }else if("WS_Archive_Save".equals(map.get("processDefinitionKey"))){
                    //归档
                    if("YS".equals(pType)){
                        mobileUrl = mobileUrl + "/dangan/#/dandianLogin?toName=archiveYB&taskId="+map.get("taskId");
                    }else {
                        mobileUrl = mobileUrl + "/dangan/#/dandianLogin?toName=archiveApproval&taskId="+map.get("taskId");
                    }
                }else if("YArchive_Save".equals(map.get("processDefinitionKey"))){
                    //预归档
                    if("YS".equals(pType)){
                        mobileUrl = mobileUrl + "/dangan/#/dandianLogin?toName=preArchivingYB&taskId="+map.get("taskId");
                    }else {
                        mobileUrl = mobileUrl + "/dangan/#/dandianLogin?toName=preArchivingApproval&taskId="+map.get("taskId");
                    }
                }
                //data.put("mobileUrl", URLEncoder.encode(mobileUrl));
                data.put("mobileUrl", mobileUrl);
                //否 流程节点
                String auditNode = "";
                data.put("auditNode",auditNode);
                //是 是否起始节点
                Boolean isStart = (Boolean) map.get("isStart");
                data.put("isStart",isStart);
                //是 是否结束节点
                Boolean isFinish = (Boolean) map.get("isFinish");
                data.put("isFinish",isFinish);
                //否 同意或不同意等等，已办任务必须填写
                String auditResult = map.get("isAgree")==null?"":(String) map.get("isAgree");
                data.put("auditResult",auditResult);
                //否 用户在界面上填写的审批意见，已办任务必须填写
                String auditView = map.get("comment")==null?"":(String) map.get("comment");
                data.put("auditView",auditView);
                //是 向用户发送消息提醒，true表示提醒，false表示不提醒
                Boolean sendMsg = true;
                data.put("sendMsg",sendMsg);
                //否 取值固定为WX，WX为中铁e通提醒。
                String msgType = "WX";
                data.put("msgType",msgType);

                JSONArray array = new JSONArray();
                array.add(data);
                String body = array.toJSONString();
                logger.info(body);

                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
                //接口调用方标识
                config.setConfigKey("consumerCode");
                String consumerCode = tenantSysConfigMapper.selectConfig(config).getConfigValue();;
                headers.set("consumerCode",consumerCode);
                //服务接口标识
                String operationCode = "";
                if("DS".equals(map.get("pType"))){
                    operationCode = "cn.crec.group.iip.ToDos.CreateV2";
                }else if("YS".equals(map.get("pType"))){
                    operationCode = "cn.crec.group.iip.ToDos.UpdateV2";
                }
                headers.set("operationCode",operationCode);
                //APP_ID
                config.setConfigKey("appId");
                String appId = tenantSysConfigMapper.selectConfig(config).getConfigValue();
                headers.set("appId",appId);

                //API密钥
                config.setConfigKey("api_secret");
                String api_secret = tenantSysConfigMapper.selectConfig(config).getConfigValue();
                String strParm="app_id="+appId+"&body="+ SyncTaskZTUtils.getSHA1(body) +"&api_secret="+api_secret;
                //签名
                String sign = MD5Utils.md5Hex(strParm.getBytes()).toUpperCase();
                headers.set("sign",sign);

                HttpEntity<String> entity = new HttpEntity<String>(body,headers);
                config.setConfigKey("syncTaskZTUrl");
                String syncTaskZTUrl = tenantSysConfigMapper.selectConfig(config).getConfigValue();
                if("DS".equals(map.get("pType"))){
                    syncTaskZTUrl = syncTaskZTUrl +"/cn.crec.group.iip.ToDos.CreateV2";
                }else if("YS".equals(map.get("pType"))){
                    syncTaskZTUrl = syncTaskZTUrl +"/cn.crec.group.iip.ToDos.UpdateV2";
                }

                ResponseEntity<String> result = restTemplate.exchange(syncTaskZTUrl, HttpMethod.POST,entity, String.class);
                //result.getStatusCode()
                String msg = result.getBody();
                logger.info(msg);
                JSONObject msjJson = JSONObject.parseObject(msg);
                if(msjJson.getInteger("code") == 100000){

                }else {
                    logger.error("同步待办失败！！！");
                }
            }
        }catch (Exception e){
            logger.error(e.getMessage(),e);
        }


    }


}
